﻿//file: charge.cpp
#include "charge.h"
#include <QPainter>
#include <QRectF>
#include <QBrush>
#include <QDebug>

/**
 * @brief 构造函数。开启一个定时器，用于改变电量，刷新界面
 * @param parent - 父对象
 */
Charge::Charge(QWidget *parent) : QWidget(parent), power(0)
{
    //设置定时器，用于改变电量
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this](){
        (power < 100) ? (this->power += 2) : (this->power = 0);
        this->update();
    });
    timer->start(500);
}

/**
 * @brief 绘图事件。绘制三个圆角矩形分别作为：电池轮廓、电池电量、电池正极，从而实现电池充电的特效。
 */
void Charge::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPen pen(Qt::darkGreen, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    QBrush brush(Qt::darkGreen, Qt::SolidPattern);

    constexpr float batteryW = 100;    //电池的宽
    constexpr float batteryH = 40;     //电池的高
    constexpr float headW = batteryW / 30;   //电池正极的宽
    constexpr float headH = batteryH / 2;   //电池正极的高

    painter.fillRect(0, 0, width(), height(), QGradient::SpringWarmth);  //绘制背景
    //根据电量设置画笔
    switch(power / 30)
    {
        case 0: pen.setColor(Qt::red);
                brush.setColor(Qt::red);
                break;
        case 1:
        case 2: pen.setColor(QColor(235,157,0));
                brush.setColor(QColor(235, 157, 0));
                break;
        case 3: pen.setColor(QColor(136,205,112));
                brush.setColor(QColor(137, 249, 83));
                break;
        default: qDebug() << __FILE__ << " : " << __FUNCTION__ << " : " <<  __LINE__ << " : power";
                 break;
    }
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);  //抗锯齿

    painter.setPen(pen);
    painter.drawRoundRect(QRectF( (width() - batteryW) / 2,    //绘制第1个圆角矩形,作为电池的主体
                                  (height() - batteryH) / 2,
                                  batteryW, batteryH),
                                  4, 4);

    painter.setBrush(brush);
    painter.drawRoundRect(QRectF( (width() + batteryW) / 2,    //绘制第2个圆角矩形,作为电池的正极
                                  (height() - headH) / 2,
                                  headW, headH),
                                  4, 4);

    //绘制电量。电量也是一个圆角矩形
    float percentage = batteryW * (power / 100.0);   //当前电量的百分比
    (percentage > 8) ? (percentage -= 8) : (percentage = 0);
    painter.drawRoundRect(QRectF( (width() - batteryW) / 2 + 4,
                                  (height() - batteryH) / 2 + 4,
                                  percentage, batteryH - 8),
                                  0, 0);

}
